/**
 * 
 */
package com.atozsoft.wf;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import java.util.TreeMap;

import com.eos.data.datacontext.DataContextManager;
import com.eos.data.datacontext.IMUODataContext;
import com.eos.data.datacontext.IUserObject;
import com.eos.system.annotation.Bizlet;
import com.eos.workflow.data.WFActivityDefine;

import commonj.sdo.DataObject;

/**
 * @author mengbq
 * @date 2014-11-12 17:16:41
 *
 */
@Bizlet("")
public class ProcessNode {
	/**
	 * activityDefID处理
	 * @author chenhe
	 * @param activityDefID 
	 * @return
	 */
	@Bizlet("")
	public static String getNextActivityDefID(String activityDefID) {
		// 例：根据riskItem02 得到 riskItem03
		String[] tempArr = activityDefID.split("_");
		int tempInt = Integer.parseInt(tempArr[1])+1;
		
		return tempArr[0] + "_0" + tempInt;
	}
	
	/**
	 * activityDefID处理
	 * @author chenhe
	 * @param activityDefID 
	 * @return
	 */
	@Bizlet("")
	public static String getPreActivityDefID(String activityDefID) {
		// 例：根据riskItem02 得到 riskItem03
		String[] tempArr = activityDefID.split("_");
		int tempInt = Integer.parseInt(tempArr[1])-1;
		
		return tempArr[0] + "_0" + tempInt;
	}
	
	/** 
	 * 获取流程节点顺序
	 * @param activityDefList 查询出的流程节点
	 * @return
	 */
	@Bizlet("")
	public static List<Map<String,String>> processNodeSort(List<WFActivityDefine> activityDefList) {
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		Map<String,String> map = new HashMap<String,String>();
		  for(WFActivityDefine ad : activityDefList){  //排除开始和结束节点，并将活动定义的Id和name存放到map中
			    String activityId = ad.getId();
			    String activityName = ad.getName();
					 if("startActivity".equals(activityId) || "finishActivity".equals(activityId)){
						 continue;
					 }else{
						 map.put(activityId, activityName);
				     }
			 }
			map =  sortMapByKey(map); //根据map的Id进行排序，即活动定义的Id进行排序
		  for(String k:map.keySet()){ //将排序后的map存放到list中
			  Map<String,String> mapTemp = new HashMap<String,String>();
			  mapTemp.put("nodeid", k);
			  mapTemp.put("nodename", map.get(k));
			  list.add(mapTemp);
		  }
		  
		  return list;
		  
	}
	
	
	
	/**
	 * 根据map的key进行排序
	 * @param oriMap 流程节点存放的map
	 * @return
	 */
	public static Map<String, String> sortMapByKey(Map<String, String> oriMap) {
		if (oriMap == null || oriMap.isEmpty()) {
			return null;
		}
		Map<String, String> sortedMap = new TreeMap<String, String>(new Comparator<String>() {
			public int compare(String key1, String key2) {
				int intKey1 = 0, intKey2 = 0;
				try {
					intKey1 = getInt(key1);
					intKey2 = getInt(key2);
				} catch (Exception e) {
					intKey1 = 0; 
					intKey2 = 0;
				}
				return intKey1 - intKey2;
			}});
		sortedMap.putAll(oriMap);
		return sortedMap;
	}
	
	/**
	 * 排序规则
	 * @param str
	 * @return
	 */
	private static int getInt(String str) {
		int i = 0;
		try {
			int n = str.lastIndexOf("_");
			if (n > 0) {
				i = Integer.valueOf(str.substring(n + 1));
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return i;
	}
	
	/** 
	 * 获取节点按钮信息
	 * @param activityDefList 查询出的流程节点
	 * @return
	 */
	@Bizlet("")
	public static List<DataObject> processNodeButtonInfo(List<DataObject> list) {
		  for(DataObject obj : list){
			  Object bObj = obj.get("buttontype");  //获取节点选择的按钮信息
			  if(bObj == null) continue;
			  String buttonType = obj.get("buttontype").toString();
			  String bName = "";
			if(buttonType.indexOf(",") > 0){                 //按钮含有多个则分组
				String[] buttonList = buttonType.split(",");
				for(int i=0,len=buttonList.length;i<len;i++){
					 String buttonInfo = buttonList[i];
					 int n = buttonInfo.indexOf("-");      //获取按钮的名称，且组合
                     if(i == len -1){
                       bName += buttonInfo.substring(n+1);
                     }else{
                       bName += buttonInfo.substring(n+1) +",";
                     }
				}
			}
		    else {                                   //按钮只有一个
			  int n = buttonType.indexOf("-");
                bName = buttonType.substring(n+1);
		    }
			obj.set("buttonName", bName);
	     }
		  
		  return list;
		  
	}

	
	/**查询当前节点的参与者是否为登录者
	 * @param participant  流程参与者
	 * @param userId  登录者
	 * @return
	 */
	@Bizlet("")
	public static boolean  processParticipantIsExist(String participant,String userId) {
		  boolean isExist = false;
		  userId = "|" + userId + "|";
		  participant = "|" + participant + "|";
          if(participant.indexOf(userId) > -1) 
        	  isExist = true;
		  return isExist;
		  
	}
	
	/**
	 * @param strSource 要替换的字符串
	 * @param strFrom  要替换的字符
	 * @param strTo 要替换成的目标字符
	 * @return
	 */
	public static String replaceFun(String strSource, String strFrom, String strTo) {    
	     if (strSource == null) {        
	       return null;    
	     }  
	     int i = 0;
	     if ((i = strSource.indexOf(strFrom, i)) >= 0) {
	       char[] cSrc = strSource.toCharArray();
	       char[] cTo = strTo.toCharArray();
	       int len = strFrom.length();  
	       StringBuffer buf = new StringBuffer(cSrc.length);  
	       buf.append(cSrc, 0, i).append(cTo);
	       i += len;    
	       int j = i;       
	       while ((i = strSource.indexOf(strFrom, i)) > 0) {  
	         buf.append(cSrc, j, i - j).append(cTo);   
	         i += len;  
	         j = i;        
	       }        
	       buf.append(cSrc, j, cSrc.length - j); 
	       return buf.toString(); 
	     } 
	     return strSource;
	   }
	
	
	/**
	 * 给设置的参数赋值
	 * @add by houfy 20150912
	 * @param variableStr  变量字符串
	 * @return map
	 */
	@Bizlet("")
	public static Map<String,Object> setProcessVariables(String variableStr) {  
		Map<String,Object> mpa = new HashMap<String,Object>();
		 if ("".equals(avoidNull(variableStr))) {        
		       return mpa;    
		 } 
		 
		if(variableStr.indexOf("☆★") > 0){                 //参数含有多个则分组
			String[] variableList = variableStr.split("☆★");
			for(String variableInfo : variableList){
				 int n = variableInfo.indexOf("-");      //获取参数的名称和值
                   String variableKey = variableInfo.substring(0,n);
                   String variableValue = variableInfo.substring(n+1);
                   mpa.put(variableKey.toString(), variableValue);
			}
		}
	    else {     //参数只有一个
	    	 int n = variableStr.indexOf("-");      //获取参数的名称和值
             String variableKey = variableStr.substring(0,n);
             String variableValue = variableStr.substring(n+1);
             mpa.put(variableKey.toString(), variableValue);
	    }
	
		return mpa;
	}
	
	  /**
	   * 判断是否为空
	 * @param str
	 * @return
	 */
	public static String avoidNull(Object str){
		  if( str == null || "".equals(str.toString().trim()) || "null".equals(str.toString().trim()))
			  return "";
		  return str.toString();
	  }
	
	public static String getUserId(){
		 IMUODataContext muo = DataContextManager.current().getMUODataContext();
		 String userId = "";
		 if(muo != null){
			 IUserObject userobject = muo.getUserObject();
				if (userobject != null) {
					userId = userobject.getUserId();
				} 
		 }
		 return userId;
	}
}
